﻿// This code is released under the BSD license.
namespace PugLib
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;

    public enum CatchResult
    {
        None = 0,
        Handled,
        Throw
    }

    public static class Patterns
    {
       

        public static void GenerateTest<T>(T value, Func<T, bool> test, Action<T> ifTrue, Action<T> ifFalse)
        {
            (test(value) ? ifTrue : ifFalse)(value);
        }

        public static void GenerateTest<T>(Func<T> generate, Func<T, bool> test, Action<T> ifTrue, Action<T> ifFalse)
        {
            T value = generate();
            (test(value) ? ifTrue : ifFalse)(value);
        }

        public static void TryFinally(Action actionProcedure, Action finallyClause)
        {
            try
            {
                actionProcedure();
            }
            finally
            {
                finallyClause();
            }
        }

        public static void TryCatch(Action actionProcedure, params CatchClause[] catchClauses)
        {
            TryCatch(actionProcedure, (IEnumerable<CatchClause>)catchClauses);
        }

        public static void TryCatch(Action actionProcedure, IEnumerable<CatchClause> catchClauses)
        {
            try
            {
                actionProcedure();
            }
            catch (Exception ex)
            {
                foreach (CatchClause catchClause in catchClauses)
                {
                    if (!catchClause.CanHandle(ex))
                    {
                    }
                    else
                    {
                        CatchResult catchResult = catchClause.Handle(ex);
                        if (catchResult == CatchResult.Handled)
                        {
                            break;
                        }
                        if (catchResult == CatchResult.Throw)
                        {
                            throw;
                        }
                        throw new InvalidEnumArgumentException("catchClauses", (int)catchResult, typeof(CatchResult));
                    }
                }
                throw; // no one handled it, so rethrow
            }
        }
    }
}